promotion = {}

promotion.pageIndex = 0;
promotion.pageSize = 100;

promotion.priceIds;
promotion.brandId;
promotion.sellerId;
promotion.catId;

promotion.page = function(page){
    promotion.pageIndex = page;
    promotion.load();
}

promotion.list = function(){
    promotion.getData();
    main.init();
    promotion.pageIndex = 0;    
    fly.ajax({
        service: '/promotion/list',
        data:{
            pageIndex: promotion.pageIndex,
            pageSize: promotion.pageSize,    
        },
        success: function(result){
            if(result.status){
                $("#content").html(fly.template('http://naima.vn/promotion/list.html',{
                    data: result.data.data
                }));       
                
                //Hiển thị link phân trang
                $('#paging').html(fly.template('http://naima.vn/component/paging.html', {
                    data:result.data,
                    action: 'promotion'
                }));

                //Hiển thị tổng số bản ghi
                $('#lbl-datacount').text(result.data.itemCount);
                
                //Link thay đổi số bản ghi trên trang
                $('#sl-page-size li[num]').removeClass('totalviewactive');
                $('#sl-page-size li[num='+result.data.pageSize+']').addClass('totalviewactive');
                
                $('#sl-page-size li[num]').click(function(){
                    promotion.pageIndex = 0;
                    promotion.pageSize = $(this).attr('num');
                    promotion.load();
                }); 
                         
            } else {
                popup.msg(result.message);
            }
        }
    });
    
}

promotion.load = function(){
    fly.ajax({
        service: '/promotion/list',
        data: {
            pageIndex: promotion.pageIndex,
            pageSize: promotion.pageSize,
        },
        success: function(result){
            if(result.status){
                //Hiển thị danh sách
                $("#content").html(fly.template('http://naima.vn/promotion/list.html',{
                    data: result.data.data
                })); 
                
                //Hiển thị link phân trang
                $('#paging').html(fly.template('http://naima.vn/component/paging.html', {
                    data:result.data,
                    action: 'promotion'
                }));

                //Hiển thị tổng số bản ghi
                $('#lbl-datacount').text(result.data.itemCount);
                
                //Link thay đổi số bản ghi trên trang
                $('#sl-page-size li[num]').removeClass('totalviewactive');
                $('#sl-page-size li[num='+result.data.pageSize+']').addClass('totalviewactive');
                
                $('#sl-page-size li[num]').click(function(){
                    promotion.pageIndex = 0;
                    promotion.pageSize = $(this).attr('num');
                    promotion.load();
                }); 
                
            } else {
                
            }
        }
    });
    
}

promotion.create = function(){
    popup.open('popup-promotion-form', 'Thêm khuyến mại mới', fly.template('http://naima.vn/promotion/form.html',{
        data: null
    }),[
    {
        title: 'Thêm mới',
        fn:function(){
            promotion.priceId = new Array;
            promotion.brandId = new Array;
            promotion.catId = new Array;
            promotion.sellerId = new Array;
            $('.price input').each(function(){
                if($(this).is(':checked'))
                    promotion.priceId.push($(this).val());
            })
            $('a[catId]').each(function(i){
                promotion.catId[i] = $(this).attr('catId');
            })            
            $('a[brandId]').each(function(i){
                promotion.brandId[i] = $(this).attr('brandId');
            })
            $('a[sellerId]').each(function(i){
                promotion.sellerId[i] = $(this).attr('sellerId');
            })
            $('.brandList').val(promotion.brandId);
            $('.catList').val(promotion.catId);
            $('.sellerList').val(promotion.sellerId);
            $('.priceList').val(promotion.priceId);
            
            fly.submit({
                id: 'promotion-form',
                service: '/promotion/create',
                success: function(result){
                    popup.msg(result.message);
                    promotion.load();
                    popup.close('popup-promotion-form');
                }
            });
        }
    },
    {
        title: 'Hủy bỏ',
        fn:function(){
            popup.close('popup-promotion-form');
        }
    },
    ]);
    promotion.rs = null;    
    promotion.getData();    
    promotion.printData('brandId', promotion.brand);
    $('.catId').html('<option value="0">Tất cả</option>');
    promotion.printCat(0, 'catId');
    promotion.printData('sellerId', promotion.seller);
    promotion.printData('discount', promotion.discount);
   
    $('.price').html('');
    $.each(promotion.price, function(){
        $('.price').append('<input type="checkbox" value="'+this.id+'">'+this.name+'</input></br>');
    });    
    $('.brandId').change(function(){
        if($(this).val() == 0)
            return;
        var tmp = this;
        var err = false;
        $.each($('a[brandId]'), function(){
            if($(this).attr('brandId') == $(tmp).val()){
                alert('Thương hiệu đã được chọn');     
                err = true;
                return false;
            }
        })                
        if(!err)
            $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) brandId="'+$(this).val()+'">'+promotion.getName(1, $(this).val())+' ,</a>')
    })
    $('.catId').change(function(){
        if($(this).val() == 0)
            return;
        var tmp = this;
        var err = false;
        $.each($('a[catId]'), function(){
            if($(this).attr('catId') == $(tmp).val()){
                alert('Danh mục đã được chọn');     
                err = true;
                return false;
            }
        })                
        if(!err)
            $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) catId="'+$(this).val()+'">'+promotion.getName(2, $(this).val())+' ,</a>')
    })
    $('.sellerId').change(function(){
        if($(this).val() == 0)
            return;
        var tmp = this;
        var err = false;
        $.each($('a[sellerId]'), function(){
            if($(this).attr('sellerId') == $(tmp).val()){
                alert('Người bán đã được chọn');     
                err = true;
                return false;
            }
        })                
        if(!err)
            $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) sellerId="'+$(this).val()+'">'+promotion.getName(3, $(this).val())+' ,</a>')
    })
    promotion.checkType();
    $('#targetType').change(function(){
        promotion.checkType();
    });
}
promotion.delAttr = function(attr){
    $(attr).remove();
}
promotion.edit = function(id){
    fly.ajax({
        service: '/promotion/get/',
        data: {
            id: id
        },
        success: function(result){            
            promotion.rs = null;
            promotion.rs = result.data;
            promotion.brandId = result.data.brandId;
            promotion.sellerId = result.data.sellerId;
            promotion.catId = result.data.categoryId;
            promotion.priceId = result.data.priceId;
            popup.open('popup-promotion-form', 'Sửa khuyến mại', fly.template('http://naima.vn/promotion/form.html',{
                data:result.data
            }),[
            {
                title: 'Sửa',
                fn:function(){
                    promotion.priceId = new Array;
                    promotion.brandId = new Array;
                    promotion.catId = new Array;
                    promotion.sellerId = new Array;
                    $('.price input').each(function(){
                        if($(this).is(':checked'))
                            promotion.priceId.push($(this).val());
                    })
                    $('a[catId]').each(function(i){
                        promotion.catId[i] = $(this).attr('catId');
                    })            
                    $('a[brandId]').each(function(i){
                        promotion.brandId[i] = $(this).attr('brandId');
                    })
                    $('a[sellerId]').each(function(i){
                        promotion.sellerId[i] = $(this).attr('sellerId');
                    })
                    $('.brandList').val(promotion.brandId);
                    $('.catList').val(promotion.catId);
                    $('.sellerList').val(promotion.sellerId);
                    $('.priceList').val(promotion.priceId);
                    fly.submit({
                        id: 'promotion-form',
                        service: '/promotion/edit',
                        success: function(rs){
                            popup.msg(rs.message);
                            promotion.load();
                            popup.close('popup-promotion-form');
                        }
                    });
                }
            },
            {
                title: 'Hủy bỏ',
                fn:function(){
                    popup.close('popup-promotion-form');
                }
            }
            ]);
            promotion.getData();    
            promotion.printData('brandId', promotion.brand);
            $('.catId').html('<option value="0">Tất cả</option>');
            promotion.printCat(0, 'catId');
            promotion.printData('sellerId', promotion.seller);
            //promotion.printData('price', promotion.price);
            promotion.printData('discount', promotion.discount);            
            $('.price').html('');
            $.each(promotion.price, function(){
                $('.price').append('<input type="checkbox" value="'+this.id+'">'+this.name+'</input></br>');
            });    
            $.each(promotion.brandId.split(','), function(i){                
                if(this != 0)
                    $('.brandId').parent().children().first().append(' <a onclick=(promotion.delAttr(this)) brandId="'+this+'">'+promotion.getName(1, this)+' ,</a>');                
            })
            $.each(promotion.catId.split(','), function(i){                
                if(this != 0)         
                    $('.catId').parent().children().first().append(' <a onclick=(promotion.delAttr(this)) catId="'+this+'">'+promotion.getName(2, this)+' ,</a>');                
            })
            $.each(promotion.sellerId.split(','), function(i){                   
                if(this != 0)          
                    $('.sellerId').parent().children().first().append(' <a onclick=(promotion.delAttr(this)) sellerId="'+this+'">'+promotion.getName(3, this)+' ,</a>');                
            })            
            $.each(promotion.priceId.split(','), function(){
                $('input[type=checkbox][value='+this+']').attr('checked','checked');
            })
            $('.brandId').change(function(){
                if($(this).val() == 0)
                    return;
                var tmp = this;
                var err = false;
                $.each($('a[brandId]'), function(){
                    if($(this).attr('brandId') == $(tmp).val()){
                        alert('Thương hiệu đã được chọn');     
                        err = true;
                        return false;
                    }
                })                
                if(!err)
                    $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) brandId="'+$(this).val()+'">'+promotion.getName(1, $(this).val())+' ,</a>')
            })
            $('.catId').change(function(){
                if($(this).val() == 0)
                    return;
                var tmp = this;
                var err = false;
                $.each($('a[catId]'), function(){
                    if($(this).attr('catId') == $(tmp).val()){
                        alert('Danh mục đã được chọn');     
                        err = true;
                        return false;
                    }
                })                
                if(!err)
                    $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) catId="'+$(this).val()+'">'+promotion.getName(2, $(this).val())+' ,</a>')
            })
            $('.sellerId').change(function(){
                if($(this).val() == 0)
                    return;
                var tmp = this;
                var err = false;
                $.each($('a[sellerId]'), function(){
                    if($(this).attr('sellerId') == $(tmp).val()){
                        alert('Người bán đã được chọn');     
                        err = true;
                        return false;
                    }
                })                
                if(!err)
                    $(this).parent().children().first().append(' <a onclick=(promotion.delAttr(this)) sellerId="'+$(this).val()+'">'+promotion.getName(3, $(this).val())+' ,</a>')
            })
            $('.discount').val(promotion.rs.discountId);             
            $('#targetType').val(promotion.rs.targetType);            
            promotion.checkType();
            $('#targetType').change(function(){
                promotion.checkType();
            });
            $('.targetId').val(promotion.rs.targetId);
        }
        
    });
     
}

promotion.del = function(id){
    popup.confirm("Bạn có chắc muốn xóa khuyến mại này ?", function(){
        fly.ajax({
            service: '/promotion/delete',
            data: {
                id:id
            },
            success: function(result){
                popup.msg(result.message);
                $(".table tr[for="+result.data+"]").remove();
            }
        });
    });
    
}

promotion.changeStatus = function(id){
    fly.ajax({
        service: '/promotion/changeStatus/',
        data: {
            id: id
        },
        success: function(data){
            if(data.status){
                if(data.data == 1)
                    $('.published-'+id).attr('src',fly.assetsUrl + '/images/icon-enable.png');
                else
                    $('.published-'+id).attr('src',fly.assetsUrl + '/images/icon-disable.png');
            }
            else
                popup.msg(data.message);
        }
    });
}
promotion.changePromotionStatus = function(id){
    fly.ajax({
        service: '/promotion/changePromotionStatus/',
        data: {
            id: id
        },
        success: function(data){
            if(data.status){
                if(data.data == 1)
                    $('.promotionpublished-'+id).attr('src',fly.assetsUrl + '/images/icon-enable.png');
                else
                    $('.promotionpublished-'+id).attr('src',fly.assetsUrl + '/images/icon-disable.png');
            }
            else
                popup.msg(data.message);
        }
    });
}
promotion.getData = function(){
    if(!promotion.brand){
        fly.ajax({
            service: '/promotion/getBrand',
            loading: false,
            async: false,
            success: function(rs){
                promotion.brand = rs.data;
            }
        })
    }
    if(!promotion.seller){
        fly.ajax({
            service: '/promotion/getSeller',
            loading: false,
            async: false,
            success: function(rs){
                promotion.seller = rs.data;
            }
        })
    }
    if(!promotion.cat){
        fly.ajax({
            service: '/promotion/getCategory',
            loading: false,
            async: false,
            success: function(rs){
                promotion.cat = rs.data;
            }
        })
    }    
    if(!promotion.price){
        fly.ajax({
            service: '/promotion/getPrice',
            loading: false,
            async: false,
            success: function(rs){
                promotion.price = rs.data;
            }
        })
    }
    if(!promotion.discount){
        fly.ajax({
            service: '/promotion/getDiscount',
            loading: false,
            async: false,
            success: function(rs){
                promotion.discount = rs.data;
            }
        })
    }
}
promotion.getName = function(type, id){
    var name = 'Tất cả';
    switch(parseInt(type)){
        case 1:
            $.each(promotion.brand, function(){
                if(this.id == id)
                    name = this.name;
            });
            break;
        case 2:
            $.each(promotion.cat, function(){
                if(this.id == id)
                    name = this.name;
            });
            break;    
        case 3:
            $.each(promotion.seller, function(){
                if(this.id == id)
                    name = this.name;
            });
            break;
        case 4:
            $.each(promotion.price, function(){
                if(this.id == id)
                    name = this.name;
            });
            break;    
        case 5:
            $.each(promotion.discount, function(){
                if(this.id == id)
                    name = this.name;
            });
            break;
            
    }
    return name;
}
promotion.level = 0;
promotion.printCat = function(parentId, clazz){
    $.each(promotion.cat, function(){
        var cat = this;
        if(cat.parentId == parentId){
            promotion.level ++;
            var tmp = "";
            var i = promotion.level;
            while(i){
                tmp += "- - ";
                i--;
            }
            $('.'+clazz).append('<option value="'+cat.id+'">'+tmp+cat.name+'</option>');
            promotion.printCat(cat.id, clazz);
            promotion.level --;
        }
    });
}
promotion.printData = function(rs, obj){
    $('.'+rs).html('<option value="0">Tất cả</option>');
    $.each(obj, function(){
        $('.'+rs).append('<option value='+this.id+'>'+this.name+'</option>')
    })   
}
promotion.checkType = function(){
    switch(parseInt($('#targetType').val())){
        case 1:
            promotion.printData('targetId', promotion.brand);
            break;
        case 2:
            $('.targetId').html('');
            promotion.printCat(0, 'targetId');
            break;
        case 3:
            $('.targetId').html('');
            promotion.printData('targetId', promotion.seller);
            break;
    }
    $('.targetId option[value=0]').remove();
}